//
//  AddReportViewController.m
//  Utils
//
//  Created by enghou on 2018/6/4.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "AddReportViewController.h"
#import "XXTextView.h"
#import "ScrollAddImageView.h"
#import "AudioViewController.h"
#import "WechatShortVideoController.h"
#import <TZImagePickerController.h>
#import "NetWorkerManager.h"
#import "FileItemModel.h"
#import "LocalPersistent.h"
#import "MSSBrowseLocalViewController.h"
#import "MSSBrowseNetworkViewController.h"
#import "VideoViewController.h"
///mobile/comprehensiveGovernance/workDiary/addWorkDiary.action
@interface AddReportViewController ()<ShowImagePicker,HandleAudio,WechatShortVideoDelegate,ShowMedia>

@property (weak, nonatomic) IBOutlet UITextField *reportTitleField;

@property (weak, nonatomic) IBOutlet XXTextView *reportContentField;

@property (weak, nonatomic) IBOutlet ScrollAddImageView *fileScrollView;

@property (weak, nonatomic) IBOutlet UILabel *organizationLabel;

@property (weak, nonatomic) IBOutlet UILabel *dateLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *containerHeight;

@end

@implementation AddReportViewController

-(void)handleAudioWithFilePath:(NSURL *)filepath{
    UIImage *image = [UIImage imageNamed:@"icon_audio"];
    MediaItemModel *model = [[MediaItemModel alloc]init];
    model.image = image;
    model.fileURL = filepath;
    [self.fileScrollView feedImage:model];
}

-(void)recordAction{
    AudioViewController *audioVC = [[AudioViewController alloc]init];
    audioVC.delegate = self;
    self.definesPresentationContext = YES;
    UIColor *color = [UIColor blackColor];
    audioVC.view.backgroundColor = [color colorWithAlphaComponent:0.5];
    audioVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [self presentViewController:audioVC animated:YES completion:nil];
}

-(void)videoAction{
    WechatShortVideoController *video = [[WechatShortVideoController alloc]init];
    video.delegate = self;
    [self push:video];
}

-(void)photoAction{
    if ([self.fileScrollView.source count] < 3) {
        TZImagePickerController *tz = [[TZImagePickerController alloc]initWithMaxImagesCount:3 - self.fileScrollView.source.count delegate:nil];
        tz.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            NSMutableArray *images = [NSMutableArray array];
            for (UIImage *photo in photos) {
                MediaItemModel *model = [[MediaItemModel alloc]init];
                model.image = photo;
                [images addObject:model];
            }
            [self.fileScrollView feedImages:images];
        };
        [self presentViewController:tz animated:YES completion:nil];
    }else{
        [self alertSome:@"最多选3个资源"];
    }
}

-(void)showPicker{
    switch (self.type) {
        case 0:
            break;
        case 1:
            //录音
            [self recordAction];
            break;
        case 2:
            //视频
            [self videoAction];
            break;
        case 3:
            //照片
            [self photoAction];
            break;
        default:
            break;
    }
}

-(void)showImageWithImage:(NSArray *)image currentIndex:(NSInteger)idx sourceView:(UIImageView *)sourceView{
    NSMutableArray *images = [NSMutableArray array];
    for (UIImage *img in image) {
        MSSBrowseModel *model = [[MSSBrowseModel alloc]init];
        model.bigImage = img;
        model.smallImageView = sourceView;
        [images addObject:model];
    }
    MSSBrowseLocalViewController *local = [[MSSBrowseLocalViewController alloc]initWithBrowseItemArray:images currentIndex:idx];
    [local showBrowseViewController];
}

-(void)showFileWithURL:(NSURL *)url{
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSString *text = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:text preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:sure];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)showAudioWithURL:(NSURL *)url{
    VideoViewController *video = [[VideoViewController alloc]init];
    video.url = url;
    [self presentViewController:video animated:YES completion:nil];
}

-(void)showVideoWithURL:(NSURL *)url{
    VideoViewController *video = [[VideoViewController alloc]init];
    video.url = url;
    [self presentViewController:video animated:YES completion:nil];
}

-(void)addSuccess{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"Refresh_WorkDaily" object:nil];
    [self pop];
}

-(void)submitActionWithParameter:(NSDictionary *)param{
    NSString *path;
    if (!self.ids) {
        path = @"/mobile/comprehensiveGovernance/workDiary/addWorkDiary.action";
    }else{
        path = [self updatePath];
    }
    [self beginLoading];
    [[NetWorkerManager sharedInstance]postWithPath:path parameter:param completeBlock:^(NSDictionary *source) {
        [self endLoading];
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        if (model.success) {
            [self addSuccess];
        }else{
            [self alertSome:model.msg];
        }
    } failBlock:^(NSInteger code) {
        [self endLoading];
        [self alertSome:kNetWorkFail];
    }];
}

-(void)submitAction{
//    workDiary.title
//    workDiary.workContent
//    workDiary.addWorkDiaryCode     新增类型编号。10:文字、30：录音、50：视频、70：相册。编号为10时，工作内容不能为空并且不能上传附件，编号为30、50、70时附件必填
//    workDiary.files[0].path
//    workDiary.files[0].suffixType
//    [self beginLoading];
    if ([self.reportTitleField.text length] == 0) {
        [self alertSome:@"请输入日志标题"];
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if (self.type == 0) {
        if ([self.reportContentField.text length] == 0) {
            [self alertSome:@"请输入工作日志内容"];
            return;
        }
        [param setObject:self.reportTitleField.text forKey:@"workDiary.title"];
        [param setObject:self.reportContentField.text forKey:@"workDiary.workContent"];
        [param setObject:@"10" forKey:@"workDiary.addWorkDiaryCode"];
        [self submitActionWithParameter:param];
    }else{
        NSString *code;
        switch (self.type) {
            case 1:
                code = @"30";
                break;
            case 2:
                code = @"50";
                break;
            default:
                code = @"70";
                break;
        }
        if (self.fileScrollView.source.count == 0) {
            [self alertSome:@"请加入附件"];
            return;
        }
        NSMutableArray *files = [NSMutableArray array];
        for (MediaItemModel *model in self.fileScrollView.source) {
            if (!model.fileURL) {
                //是个图片
                NSData *imageData = UIImageJPEGRepresentation(model.image, 0.1);
                [files addObject:imageData];
            }else{
                NSData *data = [NSData dataWithContentsOfURL:model.fileURL];
                [files addObject:data];
            }
        }
        [param setObject:code forKey:@"workDiary.addWorkDiaryCode"];
        [param setObject:self.reportTitleField.text forKey:@"workDiary.title"];
        [param setObject:self.reportContentField.text forKey:@"workDiary.workContent"];
        [self uploadFiles:files successBlock:^(NSArray<FileItemModel *> *paths) {
            [paths enumerateObjectsUsingBlock:^(FileItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *pathKey = [NSString stringWithFormat:@"workDiary.files[%li].suffixType",idx];
                NSString *typeKey = [NSString stringWithFormat:@"workDiary.files[%li].path",idx];
                [param setObject:[NSString stringWithFormat:@"%@/%@",ServerPath,obj.path] forKey:pathKey];
                [param setObject:obj.suffix forKey:typeKey];
            }];
            [self submitActionWithParameter:param];
        }];
    }
    //录音 1
    //视频 2
    //照片 3
}

-(NSString *)refresh_not_name{
    return @"Refresh_WorkDaily";
}

-(void)uploadFiles:(NSArray <NSData *>*)files successBlock:(void(^)(NSArray <FileItemModel *>*))suc{
    if (files.count > 0) {
        switch (self.type) {
            case 1:
            {
                [self beginLoading];
                [[NetWorkerManager sharedInstance]uploadAudeoWithPath:kUploadFilePath parameter:nil files:files fileName:@"file" suffix:@"wma" completeBlock:^(NSDictionary *source) {
                    [self endLoading];
                    BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:[FileItemModel class]];
                    if (model.success) {
                        if (suc) {
                            suc(model.list);
                        }
                    }else{
                        [self alertSome:model.msg];
                    }
                } failBlock:^(NSInteger code) {
                    [self endLoading];
                    [self alertSome:kNetWorkFail];
                }];
            }
                break;
            case 2:
            {
                [self beginLoading];
                [[NetWorkerManager sharedInstance]uploadAudeoWithPath:kUploadFilePath parameter:nil files:files fileName:@"file" suffix:@"mov" completeBlock:^(NSDictionary *source) {
                    [self endLoading];
                    BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:[FileItemModel class]];
                    if (model.success) {
                        if (suc) {
                            suc(model.list);
                        }
                    }else{
                        [self alertSome:model.msg];
                    }
                } failBlock:^(NSInteger code) {
                    [self endLoading];
                    [self alertSome:kNetWorkFail];
                }];
            }
            case 3:
            {
                [self beginLoading];
                [[NetWorkerManager sharedInstance]uploadAudeoWithPath:kUploadFilePath parameter:nil files:files fileName:@"file" suffix:@"jpg" completeBlock:^(NSDictionary *source) {
                    [self endLoading];
                    BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:[FileItemModel class]];
                    if (model.success) {
                        if (suc) {
                            suc(model.list);
                        }
                    }else{
                        [self alertSome:model.msg];
                    }
                } failBlock:^(NSInteger code) {
                    [self endLoading];
                    [self alertSome:kNetWorkFail];
                }];
            }
            default:
                break;
        }
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.fileScrollView.delegate = self;
    switch (self.type) {
        case 0:
            self.fileScrollView.hidden = YES;
            break;
        default:
            break;
    }
    if (!self.ids) {
        self.containerHeight.constant = 0;
    }
}

#pragma Video Delegate
- (void)finishWechatShortVideoCapture:(NSURL *)filePath{
    UIImage *image = [UIImage imageNamed:@"icon_video"];
    MediaItemModel *model = [[MediaItemModel alloc]init];
    model.image = image;
    model.fileURL = filePath;
    [self.fileScrollView feedImage:model];
}

#pragma mark - AddAndEdit

//获取工作日志详情的接口地址
-(NSString *)detailPath{
    return @"/mobile/comprehensiveGovernance/workDiary/getWorkDiaryById.action";
}

-(NSDictionary *)detailParam{
    if ([self.ids length] > 0) {
        return @{@"id":self.ids};
    }else{
        [self alertSome:@"请检查主键ID"];
        return nil;
    }
}

-(void(^)(NSDictionary *))configView{
    void(^config)(NSDictionary *) = ^(NSDictionary *source){
        NSDictionary *data = source[@"data"];
        NSDictionary *org = data[@"org"];
        NSString *orgName = org[@"orgName"];
        self.organizationLabel.text = orgName;
        NSString *time = data[@"workTime"];
        self.dateLabel.text = time;
        self.reportTitleField.text = data[@"title"];
        self.reportContentField.text = data[@"workContent"];
        NSArray *files = data[@"files"];
        NSMutableArray *items = [NSMutableArray array];
        for (NSDictionary *element in files) {
            MediaItemModel *model = [[MediaItemModel alloc]initWithSource:element];
            [items addObject:model];
        }
        [self.fileScrollView feedImages:items];
    };
    return config;
}

-(NSDictionary *)addedParameter{
    return nil;
}

-(void)addRecord{
    if ([self.reportTitleField.text length] == 0) {
        [self alertSome:@"请输入日志标题"];
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if (self.type == 0) {
        if ([self.reportContentField.text length] == 0) {
            [self alertSome:@"请输入工作日志内容"];
            return;
        }
        [param setObject:self.reportTitleField.text forKey:@"workDiary.title"];
        [param setObject:self.reportContentField.text forKey:@"workDiary.workContent"];
        [param setObject:@"10" forKey:@"workDiary.addWorkDiaryCode"];
        [self submitActionWithParameter:param];
    }else{
        NSString *code;
        switch (self.type) {
            case 1:
                code = @"30";
                break;
            case 2:
                code = @"50";
                break;
            default:
                code = @"70";
                break;
        }
        if (self.fileScrollView.source.count == 0) {
            [self alertSome:@"请加入附件"];
            return;
        }
        NSMutableArray *files = [NSMutableArray array];
        for (MediaItemModel *model in self.fileScrollView.source) {
            if (!model.fileURL) {
                //是个图片
                NSData *imageData = UIImageJPEGRepresentation(model.image, 0.1);
                [files addObject:imageData];
            }else{
                NSData *data = [NSData dataWithContentsOfURL:model.fileURL];
                [files addObject:data];
            }
        }
        [param setObject:code forKey:@"workDiary.addWorkDiaryCode"];
        [param setObject:self.reportTitleField.text forKey:@"workDiary.title"];
        [param setObject:self.reportContentField.text forKey:@"workDiary.workContent"];
        [self uploadFiles:files successBlock:^(NSArray<FileItemModel *> *paths) {
            [paths enumerateObjectsUsingBlock:^(FileItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *pathKey = [NSString stringWithFormat:@"workDiary.files[%li].suffixType",idx];
                NSString *typeKey = [NSString stringWithFormat:@"workDiary.files[%li].path",idx];
                [param setObject:[NSString stringWithFormat:@"%@/%@",ServerPath,obj.path] forKey:pathKey];
                [param setObject:obj.suffix forKey:typeKey];
            }];
            [self submitActionWithParameter:param];
        }];
    }
}

-(NSString *)updatePath{
    return @"/mobile/comprehensiveGovernance/workDiary/updateWorkDiary.action";
}

-(NSDictionary *)updateParameter{
    return nil;
}

-(void)updateRecord{
    
    if ([self.reportTitleField.text length] == 0) {
        [self alertSome:@"请输入日志标题"];
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if ([self.ids length] > 0) {
        [param setObject:self.ids forKey:@"workDiary.id"];
    }
    if (self.type == 0) {
        if ([self.reportContentField.text length] == 0) {
            [self alertSome:@"请输入工作日志内容"];
            return;
        }
        [param setObject:self.reportTitleField.text forKey:@"workDiary.title"];
        [param setObject:self.reportContentField.text forKey:@"workDiary.workContent"];
        [param setObject:@"10" forKey:@"workDiary.addWorkDiaryCode"];
        [self submitActionWithParameter:param];
    }else{
        NSString *code;
        switch (self.type) {
            case 1:
                code = @"30";
                break;
            case 2:
                code = @"50";
                break;
            default:
                code = @"70";
                break;
        }
        if (self.fileScrollView.source.count == 0) {
            [self alertSome:@"请加入附件"];
            return;
        }
        NSMutableArray *files = [NSMutableArray array];
        for (MediaItemModel *model in self.fileScrollView.source) {
            if ([model.ids length] > 0) {
                break;
            }
            if (!model.fileURL) {
                //是个图片
                NSData *imageData = UIImageJPEGRepresentation(model.image, 0.1);
                [files addObject:imageData];
            }else{
                NSData *data = [NSData dataWithContentsOfURL:model.fileURL];
                [files addObject:data];
            }
        }
        [param setObject:code forKey:@"workDiary.addWorkDiaryCode"];
        [param setObject:self.reportTitleField.text forKey:@"workDiary.title"];
        [param setObject:self.reportContentField.text forKey:@"workDiary.workContent"];
        NSMutableString *deletedFileId = [[NSMutableString alloc]init];
        [self.fileScrollView.deletedFiles enumerateObjectsUsingBlock:^(MediaItemModel * obj, NSUInteger idx, BOOL * stop) {
            [deletedFileId appendFormat:@"%@,",obj.ids];
        }];
        if (deletedFileId.length > 0) {
            deletedFileId = [[deletedFileId substringToIndex:deletedFileId.length - 2]mutableCopy];
        }
        [param setObject:deletedFileId forKey:@"workDiary.removeId"];
        if ([files count] == 0) {
            [self submitActionWithParameter:param];
            return;
        }
        [self uploadFiles:files successBlock:^(NSArray<FileItemModel *> *paths) {
            [paths enumerateObjectsUsingBlock:^(FileItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *pathKey = [NSString stringWithFormat:@"workDiary.files[%li].suffixType",idx];
                NSString *typeKey = [NSString stringWithFormat:@"workDiary.files[%li].path",idx];
                [param setObject:[NSString stringWithFormat:@"%@/%@",ServerPath,obj.path] forKey:pathKey];
                [param setObject:obj.suffix forKey:typeKey];
            }];
            [self submitActionWithParameter:param];
        }];
    }
}

-(NSString *)delPath{
    return @"/mobile/comprehensiveGovernance/workDiary/deleteWorkDiaryById.action";
}

-(NSDictionary *)delParameter{
    return @{@"id":self.ids};
}

//-(void)delRecord{
//
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
